package com.app.shop.demo.fragments;


import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import com.app.shop.demo.MyApplication;
import com.app.shop.demo.R;
import com.app.shop.demo.activitys.ChatActivity;
import com.app.shop.demo.activitys.LoginActivity;
import com.app.shop.demo.activitys.OrderListActivity;
import com.app.shop.demo.activitys.PassWordResetActivity;
import com.app.shop.demo.activitys.VideoActivity;
import com.app.shop.mylibrary.base.BaseFragment;
import com.app.shop.mylibrary.beans.EventMessage;
import com.app.shop.mylibrary.utils.DialogUtil;
import com.app.shop.mylibrary.utils.SharedPreferencesUtil;
import com.app.shop.mylibrary.utils.StringUtil;
import com.app.shop.mylibrary.utils.ToastUtil;
import com.app.shop.mylibrary.widgts.CustomDialog;
import com.facebook.drawee.view.SimpleDraweeView;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.itcase.saomiao.zxing.app.CaptureActivity;
import de.greenrobot.event.EventBus;

/**
 * A simple {@link Fragment} subclass.
 */
public class MineFragment extends BaseFragment {


    @BindView(R.id.headImg)
    SimpleDraweeView headImg;
    @BindView(R.id.tv_username_mine)
    TextView tvUsernameMine;
    @BindView(R.id.rela_logout)
    RelativeLayout relaLogout;
    private String dialog_title = "退出登录";
    private String dialog_content = "是否确定退出登录？";
    private CustomDialog customDialog;

    public MineFragment() {

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_more, container, false);
        ButterKnife.bind(this, view);
        registerEventBus();
        setSelfView();
        return view;
    }

    private void setSelfView() {
        String name = SharedPreferencesUtil.getData(getActivity(), "user", "user_name", "");
        if (StringUtil.isEmpty(name)) {
            headImg.setImageResource(R.mipmap.icon_photo_default);
            tvUsernameMine.setText("登录/注册");
            relaLogout.setVisibility(View.GONE);
        } else {
            headImg.setImageResource(R.mipmap.icon_book4);
            tvUsernameMine.setText("已登录");
            relaLogout.setVisibility(View.VISIBLE);
        }
    }


    @Override
    public void onEvent(EventMessage msg) {
        super.onEvent(msg);
        if (msg.getMessageType() == EventMessage.LOGIN) {
            tvUsernameMine.setText("已登录");
        } else if (msg.getMessageType() == EventMessage.LOGOUT) {
            MyApplication.orderList.clear();
            MyApplication.orderDetailList.clear();
            MyApplication.goodsBeanList.clear();
            SharedPreferencesUtil.removeAll(getContext(), "user");
            EventBus.getDefault().post(new EventMessage(EventMessage.REFRESH));
        }
        setSelfView();
    }

    @OnClick({R.id.rela_shipin, R.id.rela_kefu, R.id.tv_sm, R.id.rela_order, R.id.rela_pwd_reset, R.id.tv_username_mine, R.id.rela_logout})
    public void onViewClicked(View view) {

        switch (view.getId()) {
            case R.id.rela_shipin:
                if (StringUtil.isEmpty(SharedPreferencesUtil.getData(getActivity(), "user", "user_name", ""))) {
                    ToastUtil.showToast(getActivity(), "请先登录");skipActivity(getActivity(), LoginActivity.class);
                    return;
                }
                skipActivity(getActivity(), VideoActivity.class);
                break;
            case R.id.rela_kefu:
                if (StringUtil.isEmpty(SharedPreferencesUtil.getData(getActivity(), "user", "user_name", ""))) {
                    ToastUtil.showToast(getActivity(), "请先登录");skipActivity(getActivity(), LoginActivity.class);
                    return;
                }
                skipActivity(getActivity(), ChatActivity.class);
                break;
            case R.id.tv_sm:
                Open();
                break;
            case R.id.tv_username_mine:
                if (StringUtil.isEmpty(SharedPreferencesUtil.getData(getActivity(), "user", "user_name", ""))) {
                    ToastUtil.showToast(getActivity(), "请先登录");skipActivity(getActivity(), LoginActivity.class);
                    return;
                }

                break;

            case R.id.rela_order:
                if (StringUtil.isEmpty(SharedPreferencesUtil.getData(getActivity(), "user", "user_name", ""))) {
                    ToastUtil.showToast(getActivity(), "请先登录");skipActivity(getActivity(), LoginActivity.class);
                    return;
                }
                skipActivity(getActivity(), OrderListActivity.class);

                break;
            case R.id.rela_pwd_reset:
                if (StringUtil.isEmpty(SharedPreferencesUtil.getData(getActivity(), "user", "user_name", ""))) {
                    ToastUtil.showToast(getActivity(), "请先登录");skipActivity(getActivity(), LoginActivity.class);
                    return;
                }
                skipActivity(getActivity(), PassWordResetActivity.class);
                break;

            case R.id.rela_logout:
                if (StringUtil.isEmpty(SharedPreferencesUtil.getData(getActivity(), "user", "user_name", ""))) {
                    ToastUtil.showToast(getActivity(), "请先登录");skipActivity(getActivity(), LoginActivity.class);
                    return;
                }

                Logout();
                break;
        }
    }

    private void Logout() {
        customDialog = DialogUtil.showDialog(getActivity(), customDialog, 2, dialog_title, dialog_content, "取消", "确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                EventBus.getDefault().post(new EventMessage(EventMessage.LOGOUT));
            }
        });

        if (customDialog != null && !customDialog.isShowing()) {
            customDialog.show();
        }


        customDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                customDialog = null;
            }
        });
    }

    //////////////////////////////////saomiao
    private void Open() {
        if (hasPermission(new String[]{Manifest.permission.CAMERA})) {
            //有权限 打开摄像头
            doOpenCamera();
        } else {
            requestPermission(CAMERA_CODE, new String[]{Manifest.permission.CAMERA});
        }
    }

    public static final int CAMERA_CODE = 2;
    private static final int REQUEST_QRCODE = 1;

    // 读取不同的权限 摄像头 通讯录
    public boolean hasPermission(String... permissions) {

        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(getActivity(), permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    public void requestPermission(int code, String... permisions) {
        // 23 6.0
        if (Build.VERSION.SDK_INT >= 23) {
            requestPermissions(permisions, code);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        switch (requestCode) {

            // 如果返回的是 摄像头这一次 并且同意  就打开摄像头
            case CAMERA_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    doOpenCamera();
                }
                break;
        }
    }

    public void doOpenCamera() {
        //需要把请求的权限传进来  2  1 2 3
        System.out.println("打开摄像头");
        Intent intent = new Intent(getActivity(), CaptureActivity.class);
        // 打开一个新的activity 是为了 result 拿到返回结果
        startActivityForResult(intent, REQUEST_QRCODE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            // 如果使我们请求的code 并且 成功
            case REQUEST_QRCODE:
                if (resultCode == Activity.RESULT_OK) {
                    // 弹出一下扫描结果
                    String code = data.getStringExtra("SCAN_RESULT");

                    Toast.makeText(getActivity(), code, Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

}
